package com.hzlx.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
public class SecurityConfig {
    @Resource
    TokenFilter tokenFilter;
    @Resource
    AccessReactiveAuthorizationManager accessReactiveAuthorizationManager;
    @Bean
    public SecurityWebFilterChain config(ServerHttpSecurity http){
        return http
                .cors().disable()
                .authorizeExchange(ex->
                        ex.pathMatchers("/auth/login").permitAll()
                          .pathMatchers("/api/menus").permitAll()
                          .anyExchange().access(accessReactiveAuthorizationManager)
                )
                .addFilterAt(corsFilter(), SecurityWebFiltersOrder.FIRST)
                .addFilterAt(tokenFilter, SecurityWebFiltersOrder.AUTHENTICATION)
                .csrf().disable()
                .httpBasic().disable()
                .build();
    }
    @Bean
    public CorsWebFilter corsFilter(){                          // 定制跨域共享过滤器
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("http://localhost:5173");                        // 允许任何域
        config.addAllowedMethod("*");                        // 允许任何方法
        config.addAllowedHeader("*");                        // 允许任何请求头
        config.addExposedHeader("Authorization");            // 对外暴露Authorization头
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);
        return new CorsWebFilter(source);
    }
}
